<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/index.js'
// 当前路由
const router = useRouter()
// 用户信息仓库
const userStore = useUserStore()

// 搜索关键词
const keyWords = ref('')
// 用户点击搜索按钮 或在输入框内回车 的回调
const onSearch = () => {
  // 增加浏览记录 跳转 搜索列表页
  userStore.addHistory({ goodsName: keyWords })
  router.push(`/searchList/?goodsName=${keyWords.value}`)
}

// 点击垃圾桶 清空搜索记录的回调
const clearHistory = () => {
  userStore.clearHistory()
}
</script>

<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="router.go(-1)" />
    <van-search
      autocomplete="off"
      show-action
      v-model="keyWords"
      @search="onSearch"
      shape="round"
      placeholder="请输入搜索关键词"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="history">
      <div class="history-header">
        <span>最近搜索</span>
        <van-icon name="delete-o" @click="clearHistory" />
      </div>
      <ul class="history-list">
        <li v-for="item in userStore.historyList" :key="item.goodsName">
          <div
            class="history-item"
            @click="$router.push(`/searchList?goodsName=${item.goodsName}`)"
          >
            {{ item.goodsName }}
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<style lang="less">
.search {
  .van-search.van-search--show-action {
    position: relative;
  }
  .van-search__action {
    position: absolute;
    right: 0;
    top: 20%;
    background-color: #c21401;
    color: #fff;
    text-align: center;
    font-size: 14px;
    border-radius: 0 5px 5px 0;
    width: 60px;
  }
  .history {
    padding: 15px;
    .history-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      span {
        font-size: 14px;
      }
    }
    .history-list {
      display: flex;
      flex-wrap: wrap;
      //justify-content: center;
      align-items: center;
      margin: 0 auto;

      li div {
        width: 100px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        border-radius: 20px;
        border: 1px solid #efefef;
        background: #fff;
        font-size: 14px;
        margin: 10px 10px 10px 0;
      }
    }
  }
}
</style>
